using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace wicpowerTcpTool.Network
{
    /// <summary>
    /// TCP服务器类
    /// </summary>
    public class TcpServer
    {
        private TcpListener listener;
        private TcpClient client;
        private bool isRunning;
        private readonly int port;
        private CancellationTokenSource cancellationTokenSource;

        public event EventHandler<bool> ConnectionStatusChanged;
        public event EventHandler<byte[]> DataReceived;
        public event EventHandler<Exception> ErrorOccurred;

        /// <summary>
        /// 获取服务器是否正在运行
        /// </summary>
        public bool IsRunning => isRunning;

        /// <summary>
        /// 获取客户端是否已连接
        /// </summary>
        public bool IsClientConnected => client != null && client.Connected;

        /// <summary>
        /// 获取服务器端口号
        /// </summary>
        public int Port => port;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="port">监听端口</param>
        public TcpServer(int port)
        {
            this.port = port;
            this.isRunning = false;
        }

        /// <summary>
        /// 启动服务器
        /// </summary>
        public void Start()
        {
            try
            {
                cancellationTokenSource = new CancellationTokenSource();
                listener = new TcpListener(IPAddress.Any, port);
                listener.Start();
                isRunning = true;

                // 开始接受客户端连接
                Task.Run(AcceptClientsAsync, cancellationTokenSource.Token);
            }
            catch (Exception ex)
            {
                isRunning = false;
                ErrorOccurred?.Invoke(this, ex);
                throw;
            }
        }

        /// <summary>
        /// 停止服务器
        /// </summary>
        public void Stop()
        {
            try
            {
                isRunning = false;
                cancellationTokenSource?.Cancel();
                client?.Close();
                listener?.Stop();
                ConnectionStatusChanged?.Invoke(this, false);
            }
            catch (Exception ex)
            {
                ErrorOccurred?.Invoke(this, ex);
            }
        }

        /// <summary>
        /// 发送数据到客户端
        /// </summary>
        /// <param name="data">要发送的数据</param>
        public async Task SendDataAsync(byte[] data)
        {
            if (!IsClientConnected || data == null)
                return;

            try
            {
                await client.GetStream().WriteAsync(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                ErrorOccurred?.Invoke(this, ex);
            }
        }

        private async Task AcceptClientsAsync()
        {
            while (isRunning)
            {
                try
                {
                    // 等待客户端连接
                    var newClient = await listener.AcceptTcpClientAsync();

                    // 如果已有客户端连接，关闭旧连接
                    if (client != null)
                    {
                        client.Close();
                    }

                    client = newClient;
                    ConnectionStatusChanged?.Invoke(this, true);

                    // 开始接收数据
                    _ = ReceiveDataAsync();
                }
                catch (Exception ex) when (!isRunning)
                {
                    // 服务器正常停止，记录异常信息
                    ErrorOccurred?.Invoke(this, ex);
                    break;
                }
                catch (Exception ex)
                {
                    ErrorOccurred?.Invoke(this, ex);
                    break;
                }
            }
        }

        private async Task ReceiveDataAsync()
        {
            byte[] buffer = new byte[4096];

            while (IsClientConnected && isRunning)
            {
                try
                {
                    int bytesRead = await client.GetStream().ReadAsync(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        // 客户端断开连接
                        client.Close();
                        ConnectionStatusChanged?.Invoke(this, false);
                        break;
                    }

                    byte[] receivedData = new byte[bytesRead];
                    Array.Copy(buffer, receivedData, bytesRead);
                    DataReceived?.Invoke(this, receivedData);
                }
                catch (Exception ex) when (!isRunning)
                {
                    // 服务器正常停止，记录异常信息
                    ErrorOccurred?.Invoke(this, ex);
                    break;
                }
                catch (Exception ex)
                {
                    ErrorOccurred?.Invoke(this, ex);
                    client?.Close();
                    ConnectionStatusChanged?.Invoke(this, false);
                    break;
                }
            }
        }
    }
} 